import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'

export default class List extends Component {
	state = {
		users:[],//存储用户
		isFirst:true, //标识是否为初次展示
		isLoading:false, //标识是否处于加载中
		errMsg:'' //存储错误信息
	}

	componentDidMount(){
		//组件一挂在就订阅消息
		this.pid = PubSub.subscribe('updateList',(_,data)=>{
			this.setState(data)
		})
	}

	componentWillUnmount(){
		PubSub.unsubscribe(this.pid)
	}

	render() {
		const {users,isFirst,isLoading,errMsg} = this.state
		return (
			<div className="row">
				{
					isFirst ? <h1>欢迎使用</h1> :
					isLoading ? <h1>加载中.....</h1> :
					errMsg ? <h1>{errMsg.message}</h1> :
					users.map((userObj)=>{
						return (
							<div key={userObj.login} className="card">
								<a href={userObj.html_url} target="_blank" rel="noreferrer">
									<img src={userObj.avatar_url} style={{width:'100px'}} alt="avatar"/>
								</a>
								<p className="card-text">{userObj.login}</p>
							</div>
						)
					})
				}
			</div>
		)
	}
}
